<script setup lang="ts">
import type { ConsultIllness } from '@/types/consult';
import type {
  UploaderAfterRead,
  UploaderFileListItem,
} from 'vant/lib/uploader/types';
import { ref, computed, onMounted } from 'vue';
import { uploadImage } from '@/services/consult';
import { Dialog, Toast } from 'vant';
import { useConsultStore } from '@/stores/consult';
import { useRouter } from 'vue-router';

// router
const router = useRouter();
// 极速问诊store
const consultStore = useConsultStore();

// 病情事件
const timeOptions = [
  { label: '一周内', value: 1 },
  { label: '一月内', value: 2 },
  { label: '半年内', value: 3 },
  { label: '大于半年', value: 4 },
];
// 是否就诊
const flagOptions = [
  { label: '就诊过', value: 1 },
  { label: '没就诊过', value: 0 },
];

// 页面响应式数据
const form = ref<ConsultIllness>({
  illnessDesc: '',
  illnessTime: undefined,
  consultFlag: undefined,
  pictures: [],
});

// 图片数组
const fileList = ref<{ id: string; url: string }[]>([]);
// 图片读到浏览器成功
const afterRead: UploaderAfterRead = (item) => {
  console.log(item);
  // 上传之前可能错误判断
  // 一次只能处理一张图片
  if (Array.isArray(item)) return;
  // 判断file是否存在
  if (!item.file) return;
  // 准备上传图片了
  item.status = 'uploading';
  item.message = '上传中...';

  // 调用图片上传接口
  uploadImage(item.file)
    .then((res) => {
      console.log('图片上传成功', res);
      // 告诉组件图片上传成功UI显示
      item.status = 'done';
      item.message = '图片上传成功';
      // 业务处理
      item.url = res.url;
      form.value.pictures?.push(res);
    })
    .catch((err) => {
      console.log('图片上传失败', err);
      // 告诉组件图片上传失败UI显示
      item.status = 'failed';
      item.message = '图片上传失败';
    });
};
// 图片删除
const onDelete = (item: UploaderFileListItem) => {
  console.log('del', item);
  form.value.pictures = form.value.pictures?.filter(
    (pic) => !(pic.url === item.url)
  );
};

// 下一步是否禁用状态的计算
const disabled = computed(() => {
  return (
    !form.value.illnessDesc?.trim() ||
    form.value.illnessTime === undefined ||
    form.value.consultFlag === undefined
  );
});

// 下一步具体的提示
const next = () => {
  if (!form.value.illnessDesc?.trim()) return Toast('请输入病情描述');
  if (form.value.illnessTime === undefined) return Toast('请选择患病时间');
  if (form.value.consultFlag === undefined) return Toast('请选择是否就诊过');
  console.log('保存信息到store');
  consultStore.setIllness(form.value);
  console.log('跳转到下一个页面');
  router.push('/consult/patient');
};

// 数据回显判断
onMounted(() => {
  console.log('===============');
  // 有数据才回显
  if (consultStore.consult.illnessDesc) {
    // 提示用户
    Dialog.confirm({
      title: '温馨提示',
      message: '是否恢复您之前填写的病情信息呢？',
      confirmButtonText: '确认x',
      confirmButtonColor: 'var(--cp-primary)',
      cancelButtonText: '取消x',
      closeOnPopstate: false,
    })
      .then((ok) => {
        console.log('恢复数据');
        // 从store里读数据
        const { illnessDesc, illnessTime, consultFlag, pictures } =
          consultStore.consult;
        // 设置到页面上
        form.value.illnessDesc = illnessDesc;
        form.value.illnessTime = illnessTime;
        form.value.consultFlag = consultFlag;
        form.value.pictures = pictures;
        // 设置组件图片数组
        if (pictures) {
          fileList.value = pictures;
        }
        // fileList.value = pictures || [];
      })
      .catch((cancel) => {
        console.log('取消了');
      });
  }
});
</script>

<template>
  <div class="consult-illness-page">
    <CpNavBar title="图文问诊" />
    <!-- 医生提示 -->
    <div class="illness-tip van-hairline--bottom">
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <div class="info">
        <p class="tit">在线医生</p>
        <p class="tip">
          请描述你的疾病或症状、是否用药、就诊经历，需要我听过什么样的帮助
        </p>
        <p class="safe">
          <cp-icon name="consult-safe" /><span>内容仅医生可见</span>
        </p>
      </div>
    </div>
    <!-- 病情描述 -->
    <div class="illness-form">
      <van-field
        type="textarea"
        rows="3"
        placeholder="请详细描述您的病情，病情描述不能为空"
        v-model="form.illnessDesc"
      ></van-field>
      <div class="item">
        <p>本次患病多久了？</p>
        <CpRadioBtn :options="timeOptions" v-model="form.illnessTime" />
      </div>
      <div class="item">
        <p>此次病情是否去医院就诊过？</p>
        <CpRadioBtn :options="flagOptions" v-model="form.consultFlag" />
      </div>
    </div>
    <!-- 图片上传 -->
    <div class="illness-img">
      <van-uploader
        upload-icon="photo-o"
        upload-text="图片上传"
        max-count="9"
        max-size="5*1024*1024"
        v-model="fileList"
        :after-read="afterRead"
        @delete="onDelete"
      ></van-uploader>
      <p class="tip" v-if="fileList.length === 0">
        上传内容仅医生可见,最多9张图,最大5MB
      </p>
    </div>

    <!-- 下一步 -->
    <div style="padding: 0px 15px">
      <van-button
        :class="{ disabled }"
        @click="next"
        type="primary"
        block
        round
      >
        下一步
      </van-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.consult-illness-page {
  //   padding-top: 46px;
  //   医生提示
  .illness-tip {
    display: flex;
    padding: 15px;
    .img {
      width: 52px;
      height: 52px;
      border-radius: 4px;
      overflow: hidden;
      margin-top: 10px;
    }
    .info {
      flex: 1;
      padding-left: 12px;
      .tit {
        font-size: 16px;
        margin-bottom: 5px;
      }
      .tip {
        padding: 12px;
        background: var(--cp-bg);
        color: var(--cp-text3);
        font-size: 13px;
        margin-bottom: 10px;
      }
      .safe {
        font-size: 10px;
        color: var(--cp-text3);
        display: flex;
        align-items: center;
        .cp-icon {
          font-size: 12px;
          margin-right: 2px;
        }
      }
    }
  }

  //   病情描述
  .illness-form {
    padding: 15px;
    .van-field {
      padding: 0;
      &::after {
        border-bottom: none;
      }
    }
    .item {
      > p {
        color: var(--cp-text3);
        padding: 15px 0;
      }
    }
  }

  .illness-img {
    padding-top: 15px;
    padding-left: 15px;
    padding-right: 15px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    .tip {
      font-size: 12px;
      color: var(--cp-tip);
    }
    ::v-deep() {
      .van-uploader {
        &__preview {
          &-delete {
            left: -6px;
            top: -6px;
            border-radius: 50%;
            background-color: var(--cp-primary);
            width: 20px;
            height: 20px;
            &-icon {
              transform: scale(0.9) translate(-22%, 22%);
            }
          }
          &-image {
            border-radius: 8px;
            overflow: hidden;
          }
        }
        &__upload {
          border-radius: 8px;
        }
        &__upload-icon {
          color: var(--cp-text3);
        }
      }
    }
  }

  // 下一步
  .van-button {
    font-size: 16px;
    &.disabled {
      opacity: 1;
      background: #fafafa;
      color: #d9dbde;
      border: #fafafa;
    }
  }
}
</style>
